//dom加载完成后执行的js
;$(function(){
    think.use("artDialog5");
	//全选的实现
	$(".check-all").click(function(){
		$(".ids").prop("checked", this.checked);
	});
	$(".ids").click(function(){
		var option = $(".ids");
		option.each(function(i){
			if(!this.checked){
				$(".check-all").prop("checked", false);
				return false;
			}else{
				$(".check-all").prop("checked", true);
			}
		});
	});


    //ajax get请求
    $('.ajax-get').click(function(){
        var target;
        var that = this;
		var dlg;
		 var _doGet=function(){
		 	 if ( (target = $(that).attr('href')) || (target = $(that).attr('url'))||(target = $(that).attr('data-uri'))  ) {
             $.get(target).success(function(data){
                if (data.status==1) {
                    if (data.url) {
                        think.tip_success(data.info + ' 页面即将自动跳转~','alert-success');
                    }else{
                        think.tip_success(data.info,'alert-success');
                    }
                    setTimeout(function(){
                        if (data.url) {
                            location.href=data.url;
                        }else if( $(that).hasClass('no-refresh')){
                            $('#top-alert').find('button').click();
                        }else{
                            location.reload();
                        }
                    },1500);
                }else{
                    think.tip_success(data.info);
                    setTimeout(function(){
                        if (data.url) {
                            location.href=data.url;
                        }else{
                            $('#top-alert').find('button').click();
                        }
                    },1500);
                }
            });

          }	
		};

        if($(that).hasClass('confirm') ) { 
		       dlg=think.confirm('确认要执行该操作吗?',function(){
			    _doGet();
		    },function(){
              dlg.close();
		      return false;
		   });
        }else{
		    _doGet();
		}	
        return false;
    });

    //ajax get请求
    $('.ajax-getd').click(function(){
        var target;
        var that = this;
        if ( $(this).hasClass('confirm') ) {
            if(!confirm('确认要执行该操作吗?')){
                return false;
            }
        }
        if ( (target = $(this).attr('href')) || (target = $(this).attr('url')) ) {
            $.get(target).success(function(data){
                if (data.status==1) {
                    if (data.url) {
                        updateAlert(data.info + ' 页面即将自动跳转~','alert-success');
                    }else{
                        updateAlert(data.info,'alert-success');
                    }
                    setTimeout(function(){
                        if (data.url) {
                            location.href=data.url;
                        }else if( $(that).hasClass('no-refresh')){
                            $('#top-alert').find('button').click();
                        }else{
                            location.reload();
                        }
                    },1500);
                }else{
                    updateAlert(data.info);
                    setTimeout(function(){
                        if (data.url) {
                            location.href=data.url;
                        }else{
                            $('#top-alert').find('button').click();
                        }
                    },1500);
                }
            });

        }
        return false;
    });

 //ajax post submit请求
    $('.ajax-post').click(function(){
        var target,query,form;
        var target_form = $(this).attr('target-form');
        var that = this;
        var nead_confirm=false;
		var todo_confirm=false;
        var _doPost=function (target,query){
				$(that).addClass('disabled').attr('autocomplete','off').prop('disabled',true); 
				$.post(target,query).success(function(data){
						if (data.status==1) {
							if (data.url) {
								think.tip_success(data.info + ' 页面即将自动跳转~');
							}else{
								think.tip_success(data.info);
							}
							setTimeout(function(){
								$(that).removeClass('disabled').prop('disabled',false);
								if (data.url) {
									location.href=data.url;
								}else if( $(that).hasClass('no-refresh')){
									$('#top-alert').find('button').click();
								}else{
									location.reload();
								}
							},1500);
						}else{
							think.tip_success(data.info);
							setTimeout(function(){
								$(that).removeClass('disabled').prop('disabled',false);
								if (data.url) {
									location.href=data.url;
								}else{
									$('#top-alert').find('button').click();
								}
							},1500);
						}
				 });
					
		    };//end func doPost

           if( ($(that).attr('type')=='submit') || (target = $(that).attr('href')) || (target = $(that).attr('url')) ){
            form = $('.'+target_form);
            if ($(that).attr('hide-data') === 'true'){//无数据时也可以使用的功能
            	form = $('.hide-data');
            	query = form.serialize();
            }else if (form.get(0)==undefined){
            	return false;
            }else if ( form.get(0).nodeName=='FORM' ){
                   if($(that).attr('url') !== undefined){
						target = $(that).attr('url');
					}else{
						target = form.get(0).action;
					}			
					query = form.serialize();
					if ($(that).hasClass('confirm') ) {
					    todo_confirm=true;
					}
            }else if( form.get(0).nodeName=='INPUT' || form.get(0).nodeName=='SELECT' || form.get(0).nodeName=='TEXTAREA') {
                form.each(function(k,v){
                    if(v.type=='checkbox' && v.checked==true){
                        nead_confirm = true;
                    }
                })
                if ( nead_confirm && $(that).hasClass('confirm') ) {
                     todo_confirm=true;
                }
                query = form.serialize();
            }else{
                if ( $(that).hasClass('confirm') ) {
                    todo_confirm=true;
                }
                query = form.find('input,select,textarea').serialize();
            }

            if(todo_confirm){
			   	 var dlg=think.confirm('确认要执行该操作吗?',function(){				 
					_doPost(target,query);
				},function(){
				     dlg.close();
		             return false;
				});
			}else {
			     _doPost(target,query);
				 think.tip_success( '页面即将自动跳转~');
				 return false;
			}
        }
        return false;
    });

    //ajax post submit请求
    $('.ajax-postd').click(function(){
        var target,query,form;
        var target_form = $(this).attr('target-form');
        var that = this;
        var nead_confirm=false;
        if( ($(this).attr('type')=='submit') || (target = $(this).attr('href')) || (target = $(this).attr('url')) ){
            form = $('.'+target_form);

            if ($(this).attr('hide-data') === 'true'){//无数据时也可以使用的功能
            	form = $('.hide-data');
            	query = form.serialize();
            }else if (form.get(0)==undefined){
            	return false;
            }else if ( form.get(0).nodeName=='FORM' ){
                if ( $(this).hasClass('confirm') ) {
                    if(!confirm('确认要执行该操作吗?')){
                        return false;
                    }
                }
                if($(this).attr('url') !== undefined){
                	target = $(this).attr('url');
                }else{
                	target = form.get(0).action;
                }
                query = form.serialize();
            }else if( form.get(0).nodeName=='INPUT' || form.get(0).nodeName=='SELECT' || form.get(0).nodeName=='TEXTAREA') {
                form.each(function(k,v){
                    if(v.type=='checkbox' && v.checked==true){
                        nead_confirm = true;
                    }
                })
                if ( nead_confirm && $(this).hasClass('confirm') ) {
                    if(!confirm('确认要执行该操作吗?')){
                        return false;
                    }
                }
                query = form.serialize();
            }else{
                if ( $(this).hasClass('confirm') ) {
                    if(!confirm('确认要执行该操作吗?')){
                        return false;
                    }
                }
                query = form.find('input,select,textarea').serialize();
            }
            $(that).addClass('disabled').attr('autocomplete','off').prop('disabled',true);
            $.post(target,query).success(function(data){
                if (data.status==1) {
                    if (data.url) {
                        updateAlert(data.info + ' 页面即将自动跳转~','alert-success');
                    }else{
                        updateAlert(data.info ,'alert-success');
                    }
                    setTimeout(function(){
                    	$(that).removeClass('disabled').prop('disabled',false);
                        if (data.url) {
                            location.href=data.url;
                        }else if( $(that).hasClass('no-refresh')){
                            $('#top-alert').find('button').click();
                        }else{
                            location.reload();
                        }
                    },1500);
                }else{
                    updateAlert(data.info);
                    setTimeout(function(){
                    	$(that).removeClass('disabled').prop('disabled',false);
                        if (data.url) {
                            location.href=data.url;
                        }else{
                            $('#top-alert').find('button').click();
                        }
                    },1500);
                }
            });
        }
        return false;
    });


$('.list-opera').click(function(e){
   e.stopPropagation();   
   that=this;
   href=$(that).prop('href');
   var act='';
   try{
		uobj=think.parse_url(href); 
		uact=think.parse_str(uobj.query);
		act=uact.a;
   }catch(e){};
    if(act=='del'){
	   dlg=think.confirm('确定要删除此记录吗?',function(){
        $.get(href).success(function(data){
		 if (data.status==1) {
		     think.tip_success(data.info);	
		     location.reload();
		 }
	  });
     },function(){ dlg.close();return false; });
	 return false;
   }
});


	/**顶部警告栏*/
	var content = $('#main');
	var top_alert = $('#top-alert');
	top_alert.find('.close').on('click', function () {
		top_alert.removeClass('block').slideUp(200);
		// content.animate({paddingTop:'-=55'},200);
	});

    window.updateAlert = function (text,c) {
		text = text||'default';
		c = c||false;
		if ( text!='default' ) {
            top_alert.find('.alert-content').text(text);
			if (top_alert.hasClass('block')) {
			} else {
				top_alert.addClass('block').slideDown(200);
				// content.animate({paddingTop:'+=55'},200);
			}
		} else {
			if (top_alert.hasClass('block')) {
				top_alert.removeClass('block').slideUp(200);
				// content.animate({paddingTop:'-=55'},200);
			}
		}
		if ( c!=false ) {
            top_alert.removeClass('alert-error alert-warn alert-info alert-success').addClass(c);
		}
	};

    //按钮组
    (function(){
        //按钮组(鼠标悬浮显示)
        $(".btn-group").mouseenter(function(){
            var userMenu = $(this).children(".dropdown ");
            var icon = $(this).find(".btn i");
            icon.addClass("btn-arrowup").removeClass("btn-arrowdown");
            userMenu.show();
            clearTimeout(userMenu.data("timeout"));
        }).mouseleave(function(){
            var userMenu = $(this).children(".dropdown");
            var icon = $(this).find(".btn i");
            icon.removeClass("btn-arrowup").addClass("btn-arrowdown");
            userMenu.data("timeout") && clearTimeout(userMenu.data("timeout"));
            userMenu.data("timeout", setTimeout(function(){userMenu.hide()}, 100));
        });

        //按钮组(鼠标点击显示)
        // $(".btn-group-click .btn").click(function(){
        //     var userMenu = $(this).next(".dropdown ");
        //     var icon = $(this).find("i");
        //     icon.toggleClass("btn-arrowup");
        //     userMenu.toggleClass("block");
        // });
        $(".btn-group-click .btn").click(function(e){
            if ($(this).next(".dropdown").is(":hidden")) {
                $(this).next(".dropdown").show();
                $(this).find("i").addClass("btn-arrowup");
                e.stopPropagation();
            }else{
                $(this).find("i").removeClass("btn-arrowup");
            }
        })
        $(".dropdown").click(function(e) {
            e.stopPropagation();
        });
        $(document).click(function() {
            $(".dropdown").hide();
            $(".btn-group-click .btn").find("i").removeClass("btn-arrowup");
        });
    })();

    // 独立域表单获取焦点样式
    $(".text").focus(function(){
        $(this).addClass("focus");
    }).blur(function(){
        $(this).removeClass('focus');
    });
    $("textarea").focus(function(){
        $(this).closest(".textarea").addClass("focus");
    }).blur(function(){
        $(this).closest(".textarea").removeClass("focus");
    });
});

/* 上传图片预览弹出层 */

//标签页切换(无下一步)
function showTab() {
    $(".tab-nav li").click(function(){
        var self = $(this), target = self.data("tab");
        self.addClass("current").siblings(".current").removeClass("current");
        window.location.hash = "#" + target.substr(3);
        $(".tab-pane.in").removeClass("in");
        $("." + target).addClass("in");
    }).filter("[data-tab=tab" + window.location.hash.substr(1) + "]").click();
}

//标签页切换(有下一步)
function nextTab() {
     $(".tab-nav li").click(function(){
        var self = $(this), target = self.data("tab");
        self.addClass("current").siblings(".current").removeClass("current");
        window.location.hash = "#" + target.substr(3);
        $(".tab-pane.in").removeClass("in");
        $("." + target).addClass("in");
        showBtn();
    }).filter("[data-tab=tab" + window.location.hash.substr(1) + "]").click();

    $("#submit-next").click(function(){
        $(".tab-nav li.current").next().click();
        showBtn();
    });
}

// 下一步按钮切换
function showBtn() {
    var lastTabItem = $(".tab-nav li:last");
    if( lastTabItem.hasClass("current") ) {
        $("#submit").removeClass("hidden");
        $("#submit-next").addClass("hidden");
    } else {
        $("#submit").addClass("hidden");
        $("#submit-next").removeClass("hidden");
    }
}

//导航高亮
function highlight_subnav(url){
    $('.side-sub-menu').find('a[href="'+url+'"]').closest('li').addClass('current');
}



$(function(){
            //确认操作
            $('.J_confirmurl').on('click', function() {
                var self = $(this),
                        uri = self.attr('data-uri'),
                        acttype = self.attr('data-acttype'),
                        title = (self.attr('data-title') != undefined) ? self.attr('data-title') : lang.confirm_title,
                        msg = self.attr('data-msg'),
                        callback = self.attr('data-callback');
                $.dialog({
                    title: title,
                    content: msg,
                    padding: '10px 20px',
                    lock: true,
                    ok: function() {
                        if (acttype == 'ajax') {
                            $.getJSON(uri, function(result) {
                                if (result.status == 1) {
                                    think.tip_success(result.msg);
                                    if (callback != undefined) {
                                        eval(callback + '(self)');
                                    } else {
                                        window.location.reload();
                                    }
                                } else {
                                    think.tip_error(result.msg);
                                }
                            });
                        } else {
                            location.href = uri;
                        }
                    },
                    cancel: function() {
                    }
                });
            });

            //弹窗表单
            $('.J_showdialog').on('click', function() {
                var self = $(this),
                        dtitle = self.attr('data-title'),
                        did = self.attr('data-id'),
                        duri = self.attr('data-uri'),
                        dwidth = parseInt(self.attr('data-width')),
                        dheight = parseInt(self.attr('data-height')),
                        dpadding = (self.attr('data-padding') != undefined) ? self.attr('data-padding') : '10px 20px',
                        poptype = (self.attr('data-poptype') != undefined) ? self.attr('data-poptype') : 'edit',                     
                        dcallback = self.attr('data-callback');
                        var options={
                                id: did,
                                title: dtitle,
                                width: dwidth ? dwidth : 'auto',
                                height: dheight ? dheight : 'auto',
                                padding: dpadding,
                                lock: true,
                                okValue:'提交',
                                cancelValue:'取消',
                                cancel: function() {}
                            };
                        if(poptype!='view'){
                                options.ok= function() {
                                var info_form = this.dom.content.find('#info_form');
                                if (info_form[0] != undefined) {
                                    info_form.submit();
                                    if (dcallback != undefined) {
                                        eval(dcallback + '()');
                                    }
                                    return false;
                                }
                                if (dcallback != undefined) {
                                    eval(dcallback + '()');
                                }
                              }
                        }

                $.dialog({id: did}).close();
                $.dialog(options);
                $.getJSON(duri, function(result) {
                    if (result.status == 1) {
                        $.dialog.get(did).content(result.data);

                        $("select").select2({
                            templateResult:formatState
                        });
                    }
                });
                return false;
            });
    function formatState (state) {
        if (!state.id) { return state.text; }
        var $state = $(
            '<span class="'+state.element.getAttribute("testcolor")+'">' + state.text + '</span>'
        );
        return $state;
    };
            //附件预览
            $('.J_attachment_icon').on('mouseover', function() {
                var ftype = $(this).attr('file-type');
                var rel = $(this).attr('file-rel');
                switch (ftype) {
                    case 'image':
                        if (!$(this).find('.attachment_tip')[0]) {
                            $('<div class="attachment_tip"><img src="' + rel + '" /></div>').prependTo($(this)).fadeIn();
                        } else {
                            $(this).find('.attachment_tip').fadeIn();
                        }
                        break;
                }
            }).on('mouseout', function() {
                $('.attachment_tip').hide();
            });

            $('.J_attachment_icons').on('mouseover', function() {
                var ftype = $(this).attr('file-type');
                var rel = $(this).attr('file-rel');
                switch (ftype) {
                    case 'image':
                        if (!$(this).find('.attachment_tip')[0]) {
                            $('<div class="attachment_tip" style="width:160px; height:80px;"><img width="160" height="80" src="' + rel + '" /></div>').prependTo($(this)).fadeIn();
                        } else {
                            $(this).find('.attachment_tip').fadeIn();
                        }
                        break;
                }
            }).on('mouseout', function(){
		$('.attachment_tip').hide();
	});
});

/**
图片查看
第一种用法：
<a href='' class='preview'><img src='s.jpg' data-bigsrc='b.jpg'></a>
$('.preview').Preview();

第二种用法：
<img src='s.jpg' data-bigsrc='b.jpg'  class='preview'>
$('.preview').Preview();
**/
$.fn.ImgPreview = function(){
	xOffset = 10;
	yOffset = 30;
	cssStr="position:absolute;border:1px solid #ccc;background:#333;padding:5px;display:none;color:#fff;z-index:65530";
	_that=this;
	$(this).hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		var tag=this.tagName;
		var w,h;
        if(tag=='IMG'){
			bigsrc=$(this).data('bimg');
			ssize=$(this).data('size');		  
		}else{
		    bigsrc=$(this).find('img').data('bimg');
			ssize=$(this).find('img').data('size');		
		} 
		if(ssize){
		    tmparr=ssize.split(',');
			if(tmparr[0])w=parseInt(tmparr[0]);
			if(tmparr[1])h=parseInt(tmparr[1]);
		}
		$("body").append("<div id='preview' style='"+cssStr+"'><img src='"+ bigsrc +"' />"+ c +"</div>");
		if(w){
		   $("#preview").css("width",w + "px")
		 }
		if(h){
		   $("#preview").css("height",w + "px")
		}
		$("#preview").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px").fadeIn("fast");						
    },
	function(){		 
		$("#preview").remove();
    });	
	$(_that).mousemove(function(e){
		$("#preview").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px");
	});	
}